﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Diagnostics;

namespace TfsExtensions.Build.Activities
{
    public sealed class InvokeXslTransformForTocXml : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> SandcastleProductionToolsFolder { get; set; }

        [RequiredArgument]
        public InArgument<string> SandcastleTransformsFolder { get; set; }

        [RequiredArgument]
        public InArgument<string> SandcastleXformToc { get; set; }

        [RequiredArgument]
        public InArgument<string> WorkingFolderName { get; set; }

        [RequiredArgument]
        public InArgument<string> ReflectionXMLFilename { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // This activity runs following command.
            //  <Exec Command="&quot;$(TransformEXE)&quot; /xsl:&quot;$(SandcastleTransformsFolder)\$(SandcastleXformToc)&quot; $(WorkingFolderName)\$(ReflectionXMLFilename) /out:$(WorkingFolderName)\TOC.xml" />
            var workingFolderName = this.WorkingFolderName.Get(context);
            var sandcastleXformToc = this.SandcastleXformToc.Get(context);
            var reflectionXMLFilename = this.ReflectionXMLFilename.Get(context);

            var exeFileName = string.Format(@"{0}\XslTransform.exe", this.SandcastleProductionToolsFolder.Get(context));
            var sandcastleTransformPath = "/xsl:\"" + string.Format(@"{0}\{1}", this.SandcastleTransformsFolder.Get(context), sandcastleXformToc) + "\"";
            var reflectionWorkingFolderPath = "\"" + string.Format(@"{0}\{1}", workingFolderName, reflectionXMLFilename) + "\"";
            var outputPath = "\"" + string.Format("{0}\\TOC.xml", workingFolderName) + "\"";
            var arguments = string.Format("{0} {1} /out:{2}", sandcastleTransformPath, reflectionWorkingFolderPath, outputPath);
            try
            {
                InvokeCommand.ExecuteCommand(context, exeFileName, arguments);
            }
            catch(Exception ex)
            {
                LogHelper.LogError(context, ex.Message);
                throw;
            }
        }
    }
}
